<!-- src/views/GoodsDetailView.vue -->
<template>
  <div class="goods-detail-page">
    <!-- 主体内容 -->
    <div class="main-content">
      <!-- 顶部导航栏 -->
      <div class="top-nav">
        <div class="nav-left">
          <router-link to="/" class="back-link">← 返回首页</router-link>
        </div>
        <div class="nav-center">
          <h1>商品详情</h1>
        </div>
        <div class="nav-right">
          <span v-if="userInfo.username" class="user-info">{{ userInfo.username }}</span>
          <span v-else class="user-info">未登录</span>
        </div>
      </div>

      <!-- 商品详情主体 -->
      <div class="goods-detail-container" v-if="goodsDetail?.id">
        <div class="goods-card">
          <!-- 图片展示 -->
          <div class="goods-image">
            <img :src="goodsDetail.gImage" alt="商品图片" @error="handleImageError" />
          </div>

          <!-- 商品信息 -->
          <div class="goods-info">
            <h2>{{ goodsDetail.gName }}</h2>

            <!-- 商品参数 -->
            <div class="goods-meta">
              <p><strong>分类：</strong>{{ goodsDetail.category?.cName || '未知分类' }}</p>
              <p><strong>库存：</strong>{{ goodsDetail.gNumber || 0 }} 件</p>
              <p><strong>评分：</strong><Stars :rating="4.5" /></p>
            </div>

            <div class="goods-types">
              <p><strong>种类：</strong></p>
              <div class="type-tags">
                <template v-if="goodsDetail.types && goodsDetail.types.length">
                  <span
                    v-for="type in goodsDetail.types"
                    :key="type.tId"
                    :style="{ backgroundColor: type.tColor }"
                    class="type-tag"
                    >{{ type.tName }}</span
                  >
                </template>
                <span v-else class="no-types">暂无种类信息</span>
              </div>
            </div>

            <!-- 价格 -->
            <p class="price">价格：￥{{ goodsDetail.gPrice }}/斤</p>

            <!-- 描述 -->
            <p class="description">描述：{{ goodsDetail.gDesciption }}</p>

            <!-- 数量选择器 -->
            <div class="quantity">
              <label>数量：</label>
              <el-input-number v-model="quantity" :min="1" :max="goodsDetail.gNumber" />
            </div>

            <!-- 按钮区域 -->
            <div class="action-buttons">
              <button class="buy-button" @click="buyNow(goodsDetail)">立即购买</button>
              <button class="cart-button" @click="addToCart(goodsDetail)">加入购物车</button>
            </div>
          </div>
        </div>

        <!-- 商品详情 Tabs -->
        <el-tabs type="card" class="goods-tabs">
          <el-tab-pane label="商品详情">
            <div v-html="goodsDetail.gDetail || '暂无详情'"></div>
          </el-tab-pane>
          <el-tab-pane label="商品评价">
            <div v-if="reviews.length">
              <div v-for="review in reviews" :key="review.id" class="review-item">
                <p><strong>{{ review.user }}</strong>: {{ review.comment }}</p>
                <p>评分：{{ review.rating }}/5</p>
              </div>
            </div>
            <div v-else>暂无评价</div>
          </el-tab-pane>
          <el-tab-pane label="推荐商品">
            <div class="recommendations">
              <div
                class="recommendation-card"
                v-for="item in filteredRecommendedGoods"
                :key="item.id"
                @click="goToDetail(item)"
              >
                <img :src="item.gImage" alt="推荐商品" @error="handleImageError" />
                <p>{{ item.gName }}</p>
                <p>￥{{ item.gPrice }}</p>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <div v-else class="loading">加载中...</div>

      <!-- 底部 -->
      <FooterBar />
    </div>

    <!-- 立即购买弹窗 -->
    <el-dialog v-model="buyDialogVisible" title="确认购买" width="800px">
      <!-- 在弹窗顶部添加 logo 图片 -->
      <template #title>
        <div style="display: flex; align-items: center;">
          <img src="@/assets/images/logo.jpg" alt="Logo" style="width: 40px; height: auto; margin-right: 10px;" />
          <span>确认购买</span>
        </div>
      </template>
      <div class="buy-dialog-content">
        <!-- 左侧商品图片 -->
        <div class="buy-dialog-image">
          <img :src="goodsDetail.gImage" alt="商品图片" style="width: 200px; height: 200px; object-fit: cover;" />
        </div>

        <!-- 右侧商品信息 -->
        <div class="buy-dialog-info">
          <div>
            <div>
              <h3>{{ goodsDetail.gName }}</h3>
              <p><strong>价格：</strong>￥{{ goodsDetail.gPrice }}/斤</p>
              <p><strong>库存：</strong>{{ goodsDetail.gNumber }} 件</p>
              <p><strong>评分：</strong><Stars :rating="4.5" /></p>
            </div>
            <div class="buy-dialog-quantity">
              <label>数量：</label>
              <el-input-number v-model="quantity" :min="1" :max="goodsDetail.gNumber" />
            </div>
            <div class="buy-dialog-types">
              <p><strong>种类：</strong></p>
              <div class="type-tags">
                <template v-if="goodsDetail.types && goodsDetail.types.length">
                  <span
                    v-for="type in goodsDetail.types"
                    :key="type.tId"
                    :style="{ backgroundColor: type.tColor }"
                    class="type-tag"
                    >{{ type.tName }}</span
                  >
                </template>
                <span v-else class="no-types">暂无种类信息</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="buyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmBuyNow">
            确认购买
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 加入购物车弹窗 -->
    <el-dialog v-model="cartDialogVisible" title="加入购物车" width="800px">
      <!-- 在弹窗顶部添加 logo 图片 -->
      <template #title>
        <div style="display: flex; align-items: center;">
          <img src="@/assets/images/logo.jpg" alt="Logo" style="width: 40px; height: auto; margin-right: 10px;" />
          <span>加入购物车</span>
        </div>
      </template>
      <div class="buy-dialog-content">
        <!-- 左侧商品图片 -->
        <div class="buy-dialog-image">
          <img :src="goodsDetail.gImage" alt="商品图片" style="width: 200px; height: 200px; object-fit: cover;" />
        </div>

        <!-- 右侧商品信息 -->
        <div class="buy-dialog-info">
          <div>
            <div>
              <h3>{{ goodsDetail.gName }}</h3>
              <p><strong>价格：</strong>￥{{ goodsDetail.gPrice }}/斤</p>
              <p><strong>库存：</strong>{{ goodsDetail.gNumber }} 件</p>
              <p><strong>评分：</strong><Stars :rating="4.5" /></p>
            </div>
            <div class="buy-dialog-quantity">
              <label>数量：</label>
              <el-input-number v-model="quantity" :min="1" :max="goodsDetail.gNumber" />
            </div>
            <div class="buy-dialog-types">
              <p><strong>种类：</strong></p>
              <div class="type-tags">
                <template v-if="goodsDetail.types && goodsDetail.types.length">
                  <span
                    v-for="type in goodsDetail.types"
                    :key="type.tId"
                    :style="{ backgroundColor: type.tColor }"
                    class="type-tag"
                    >{{ type.tName }}</span
                  >
                </template>
                <span v-else class="no-types">暂无种类信息</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cartDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddToCart">
            确认加入购物车
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import searchApi from '@/api/search'
import goodApi from '@/api/controller'
import store from '@/store'
import Stars from '@/components/Stars.vue'
import FooterBar from '@/components/FooterBar.vue'
import { ElMessage } from 'element-plus'

// 图片导入
import placeholderImage from '@/assets/images/placeholder.jpg'

const route = useRoute()
const router = useRouter()

const goodsDetail = ref(null)
const quantity = ref(1)
const recommendedGoods = ref([])
const filteredRecommendedGoods = ref([])
const userInfo = computed(() => store.getters.getUserInfo)
const buyDialogVisible = ref(false)
const cartDialogVisible = ref(false)

const reviews = [
  { id: 1, user: '用户A', comment: '非常好用！', rating: 5 },
  { id: 2, user: '用户B', comment: '一般般', rating: 3 }
]

const recommendedKeywords = ['苹果', '牛奶', '鸡蛋', '洗发水', '纸巾']

const loadGoodsDetail = async () => {
  const { id } = route.params
  try {
    const response = await searchApi.getGoodMatchById(id)
    if (response?.code === 200 && response?.data) {
      const data = response.data
      data.types = data.types || []
      goodsDetail.value = data
      quantity.value = 1
    } else {
      goodsDetail.value = null
      alert('加载商品失败')
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    goodsDetail.value = null
    alert('网络异常')
  }

  await fetchRecommendedGoods()
}

async function fetchRecommendedGoods() {
  try {
    const results = []
    for (const keyword of recommendedKeywords) {
      const response = await goodApi.getGoodListPage(1, 10, keyword)
      if (response.code === 200 && Array.isArray(response.rows)) {
        results.push(...response.rows)
      }
    }

    const uniqueResults = results.filter(
      (item, index, self) => index === self.findIndex((t) => t.id === item.id)
    )

    recommendedGoods.value = uniqueResults
    filteredRecommendedGoods.value = uniqueResults.filter(
      (item) => item.id !== goodsDetail.value?.id
    )
  } catch (error) {
    console.error('获取推荐商品失败:', error)
    recommendedGoods.value = []
    filteredRecommendedGoods.value = []
  }
}

function handleImageError(event) {
  event.target.src = placeholderImage
}

function buyNow(good) {
  buyDialogVisible.value = true
}

function addToCart(good) {
  cartDialogVisible.value = true
}

function confirmAddToCart() {
  // 检查用户是否已登录
  if (!userInfo.value || !userInfo.value.username) {
    router.push('/login')
    return
  }
  
  // 创建购物车项目对象
  const cartItem = {
    id: goodsDetail.value.id,
    gImage: goodsDetail.value.gImage,
    gName: goodsDetail.value.gName,
    gPrice: goodsDetail.value.gPrice,
    quantity: quantity.value
  }

  // 获取当前用户的购物车
  const userCartKey = `cart_${userInfo.value.username}`
  let userCart = JSON.parse(localStorage.getItem(userCartKey) || '[]')
  
  // 检查商品是否已在购物车中
  const existingItem = userCart.find(item => item.id === cartItem.id)
  if (existingItem) {
    // 如果已存在，增加数量
    existingItem.quantity += cartItem.quantity
  } else {
    // 如果不存在，添加新商品
    userCart.push(cartItem)
  }
  
  // 保存购物车到 localStorage
  localStorage.setItem(userCartKey, JSON.stringify(userCart))
  
  // 关闭弹窗
  cartDialogVisible.value = false
  
  // 使用 Element Plus 的消息提示替换 alert
  ElMessage({
    message: ` ${goodsDetail.value.gName} 已成功加入购物车`,
    type: 'success',
    duration: 2000,
    showClose: true
  })
  
  // 跳转到购物车页面
  router.push('/cart')
}

function goToDetail(good) {
  const { id } = good
  router.push({ name: 'GoodsDetail', params: { id } })
}

function confirmBuyNow() {
  alert(`立即购买：${goodsDetail.value.gName} x ${quantity.value} 件`)
  buyDialogVisible.value = false
}

function handleClose(done) {
  done()
}

watch(
  () => route.params.id,
  async (newId) => {
    if (newId) {
      await loadGoodsDetail()
    }
  },
  { immediate: true }
)

loadGoodsDetail()
</script>

<style scoped>
.goods-detail-page {
  display: flex;
  font-family: Arial, sans-serif;
  min-height: 100vh;
  background-color: #f9f9f9;
}

/* 主体内容 */
.main-content {
  flex: 1;
  margin: 0 auto;
  width: 1200px;
  padding: 20px;
}

/* 顶部导航栏 */
.top-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #2e7d32;
  color: white;
  padding: 15px 30px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
  width: 1600px;
  margin: 0 auto;
}

.top-nav .back-link {
  color: white;
  text-decoration: none;
  font-size: 16px;
}

.top-nav .back-link:hover {
  text-decoration: underline;
}

.top-nav h1 {
  margin: 0;
  font-size: 20px;
}

.top-nav .user-info {
  font-size: 14px;
  margin-left: 10px;
}

/* 商品详情容器 */
.goods-detail-container {
  width: 1400px;
  margin: 40px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.goods-card {
  display: flex;
  flex-wrap: wrap;
  gap: 40px;
  align-items: center;
}

.goods-image {
  flex: 1 1 40%;
  min-width: 250px;
}

.goods-image img {
  width: 100%;
  height: auto;
  object-fit: cover;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.goods-info {
  flex: 1 1 50%;
  min-width: 250px;
}

.goods-info h2 {
  font-size: 24px;
  margin-bottom: 20px;
}

.goods-meta {
  margin-bottom: 15px;
  font-size: 14px;
  color: #666;
}

.goods-types {
  margin-bottom: 20px;
}

.type-tags {
  display: flex;
  gap: 10px;
  margin-top: 8px;
}

.type-tag {
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 14px;
  color: black;
}

.price {
  font-size: 20px;
  color: #e53935;
  margin-bottom: 15px;
}

.description {
  font-size: 16px;
  color: #555;
  line-height: 1.6;
  margin-bottom: 30px;
}

.quantity {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 15px;
}

.buy-button,
.cart-button {
  border: none;
  border-radius: 6px;
  padding: 12px 24px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.buy-button {
  background-color: #e53935;
  color: white;
}

.buy-button:hover {
  background-color: #c62828;
}

.cart-button {
  background-color: #4caf50;
  color: white;
}

.cart-button:hover {
  background-color: #388e3c;
}

.goods-tabs {
  margin-top: 40px;
}

.recommendations {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.recommendation-card {
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 15px;
  width: 200px;
  text-align: center;
  cursor: pointer;
  transition: box-shadow 0.3s;
}

.recommendation-card:hover {
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.recommendation-card img {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
}

.review-item {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 6px;
}

.loading {
  text-align: center;
  font-size: 18px;
  color: #666;
  margin: 60px 0;
}

/* 弹窗样式 */
.buy-dialog-content {
  display: flex;
  gap: 20px;
  align-items: center;
}
.buy-dialog-image {
  flex: 0 0 200px;
}
.buy-dialog-info {
  flex: 1;
}
.buy-dialog-quantity {
  margin-top: 10px;
}
.buy-dialog-types {
  margin-top: 10px;
}

.el-dialog {
  background-color: #f0f0f0; /* 更柔和的背景颜色 */
  width: 800px !important;
}

.el-dialog__header {
  background-color: #2e7d32; /* 超市主题颜色 */
  color: white;
}

.el-dialog__footer {
  background-color: #f0f0f0; /* 与弹窗背景颜色一致 */
}
</style>